//
//  MineOrderViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/7/31.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "MineOrderViewController.h"
#import "OrderStatusModel.h"
#import "MineOrderHeaderView.h"
#import "MineOrderTableViewCell.h"
#import "OrderModel.h"
#import "OrderDetailViewController.h"
#import "EvaluateViewController.h"
//#import "LogisticsViewController.h"
#import "LogisticsWebViewController.h"
#import "RefundDetailViewController.h"
#import "PayStatusViewController.h"
#import "PayView.h"
#import "OthersMemberInfoModel.h"
//#import "OthersStoreViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DYShopOrderFooterView.h"

#import <Masonry/Masonry.h>

@interface MineOrderViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *headerTitleArray;
// 全部
@property (nonatomic, strong) NSMutableArray<OrderModel *> *tableArrayAll;
@property (nonatomic, assign) NSInteger pageAll;
// 待付款
@property (nonatomic, strong) NSMutableArray<OrderModel *> *tableArrayObligation;
@property (nonatomic, assign) NSInteger pageObligation;
// 待发货
@property (nonatomic, strong) NSMutableArray<OrderModel *> *tableArrayDelivery;
@property (nonatomic, assign) NSInteger pageDelivery;
// 待收货
@property (nonatomic, strong) NSMutableArray<OrderModel *> *tableArrayReceived;
@property (nonatomic, assign) NSInteger pageReceived;
// 待评价
@property (nonatomic, strong) NSMutableArray<OrderModel *> *tableArrayEvaluation;
@property (nonatomic, assign) NSInteger pageEvaluation;

@property (nonatomic, strong) MineOrderHeaderView *headerView;

@property (nonatomic, strong) PayView *payView;

@property (nonatomic,strong) DYShopOrderFooterView * footerView;

@end

@implementation MineOrderViewController
#pragma mark - Get
- (NSMutableArray<OrderModel *> *)tableArrayAll {
    if (!_tableArrayAll) {
        _tableArrayAll = [[NSMutableArray alloc] init];
    }
    return _tableArrayAll;
}
- (NSMutableArray<OrderModel *> *)tableArrayObligation {
    if (!_tableArrayObligation) {
        _tableArrayObligation = [[NSMutableArray alloc] init];
    }
    return _tableArrayObligation;
}
- (NSMutableArray<OrderModel *> *)tableArrayDelivery {
    if (!_tableArrayDelivery) {
        _tableArrayDelivery = [[NSMutableArray alloc] init];
    }
    return _tableArrayDelivery;
}
- (NSMutableArray<OrderModel *> *)tableArrayReceived {
    if (!_tableArrayReceived) {
        _tableArrayReceived = [[NSMutableArray alloc] init];
    }
    return _tableArrayReceived;
}
- (NSMutableArray<OrderModel *> *)tableArrayEvaluation {
    if (!_tableArrayEvaluation) {
        _tableArrayEvaluation = [[NSMutableArray alloc] init];
    }
    return _tableArrayEvaluation;
}

- (NSArray *)headerTitleArray {
    if (!_headerTitleArray) {
        _headerTitleArray = [[NSMutableArray alloc] init];
        [_headerTitleArray addObject:@{@"title":@"全部",@"number":@"0"}];
        [_headerTitleArray addObject:@{@"title":@"待付款",@"number":@"0"}];
        [_headerTitleArray addObject:@{@"title":@"待发货",@"number":@"0"}];
        [_headerTitleArray addObject:@{@"title":@"待收货",@"number":@"0"}];
        [_headerTitleArray addObject:@{@"title":@"待评价",@"number":@"0"}];
    }
    return _headerTitleArray;
}
- (PayView *)payView {
    if (!_payView) {
        _payView = [[PayView alloc] initWithFrame:Screen];
    }
    return _payView;
}
#pragma mark - viewController
- (instancetype)init {
    self = [super init];
    if (self) {
        _classType = MineOrderClassTypeNormal;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的订单";
    if (self.classType == MineOrderClassTypeGroup) {
        self.title = @"我的团购";
    }
    
    [self createHeaderView];
    [self setupTableView];
    if (self.soldType == 0) {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(50, 0, 0, 0));
        }];
    }else{
        [self.view addSubview:self.footerView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(50, 0, 50, 0));
        }];
        [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
        }];
    }
    
   
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getNetStatusData];
}
- (void)disMissSelf {
    [self popToRootViewController];
}
#pragma mark - action
- (void)createHeaderView {
    __block typeof(self) blockSelf = self;
    self.headerView = [[MineOrderHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 45.0) titleArray:self.headerTitleArray selectIndex:self.type];
    _headerView.block = ^(NSInteger tag) {
        NSLog(@"点击 %ld",tag);
        [blockSelf.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.003 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            blockSelf.type = tag-200;
            [blockSelf getNetStatusData];
            [blockSelf getNetData];
        });
    };
    [self.view addSubview:_headerView];
}
- (void)updateHeaderView {
    [self.headerView updateWith:self.headerTitleArray];
}
- (void)setupTableView {
    self.pageAll = 1;
    self.pageObligation = 1;
    self.pageDelivery = 1;
    self.pageReceived = 1;
    self.pageEvaluation = 1;
    
    [self.tableView clearExtendCellLine];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        switch (self.type) {
            case MineOrderTypeAll:
                _pageAll++;
                break;
            case MineOrderTypeObligation:
                _pageObligation++;
                break;
            case MineOrderTypeDelivery:
                _pageDelivery++;
                break;
            case MineOrderTypeReceived:
                _pageReceived++;
                break;
            case MineOrderTypeEvaluation:
                _pageEvaluation++;
                break;
            default:
                break;
        }
        [self getNetData];
    }];
    [self.tableView.mj_footer setHidden:YES];
}
- (void)reloadData {
    switch (self.type) {
        case MineOrderTypeAll:
            _pageAll = 1;
            break;
        case MineOrderTypeObligation:
            _pageObligation = 1;
            break;
        case MineOrderTypeDelivery:
            _pageDelivery = 1;
            break;
        case MineOrderTypeReceived:
            _pageReceived = 1;
            break;
        case MineOrderTypeEvaluation:
            _pageEvaluation = 1;
            break;
        default:
            break;
    }
    [self getNetStatusData];
    [self getNetData];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    switch (self.type) {
        case MineOrderTypeAll:
            if (_pageAll != 1) {
                _pageAll--;
            }
            break;
        case MineOrderTypeObligation:
            if (_pageObligation != 1) {
                _pageObligation--;
            }
            break;
        case MineOrderTypeDelivery:
            if (_pageDelivery != 1) {
                _pageDelivery--;
            }
            break;
        case MineOrderTypeReceived:
            if (_pageReceived != 1) {
                _pageReceived--;
            }
            break;
        case MineOrderTypeEvaluation:
            if (_pageEvaluation != 1) {
                _pageEvaluation--;
            }
            break;
        default:
            break;
    }
    [self.tableView reloadData];
}
- (void)getNetSuccess:(NSDictionary *)dics {
    NSInteger page = 1;
    NSMutableArray *tableArray;
    switch (self.type) {
        case MineOrderTypeAll:
            page = _pageAll;
            tableArray = self.tableArrayAll;
            break;
        case MineOrderTypeObligation:
            page = _pageObligation;
            tableArray = self.tableArrayObligation;
            break;
        case MineOrderTypeDelivery:
            page = _pageDelivery;
            tableArray = self.tableArrayDelivery;
            break;
        case MineOrderTypeReceived:
            page = _pageReceived;
            tableArray = self.tableArrayReceived;
            break;
        case MineOrderTypeEvaluation:
            page = _pageEvaluation;
            tableArray = self.tableArrayEvaluation;
            break;
        default:
            break;
    }
    
    if ([dics[@"data"][@"totalRow"] integerValue] > tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (page == 1) {
        [tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *arr = dics[@"data"][@"list"];
    if (arr.count == 0 && page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dataDic in arr) {
        OrderModel *model = [OrderModel mj_objectWithKeyValues:dataDic];
        [tableArray addObject:model];
    }
    [self.tableView reloadData];
}

- (void)uploadWechatPay:(NSDictionary *)parameters {
    /*
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"没有安装微信" animated:YES];
        return;
    }
    if (![WXApi isWXAppSupportApi]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"当前微信版本过低" animated:YES];
        return;
    }
    
    PayReq *request   = [[PayReq alloc] init];
    //request.openID    = responseObject[@"data"][@"appId"];
    request.partnerId = Wechat_partnerId;
    request.prepayId  = parameters[@"prepayid"];
    request.package   = parameters[@"package"];//Sign=WXPay
    request.nonceStr  = parameters[@"noncestr"];
    request.timeStamp = [parameters[@"timestamp"] unsignedIntValue];
    request.sign      = parameters[@"sign"];
    if ([WXApi sendReq:request]) {
        NSLog(@"发送成功");
        
    } else {
        NSLog(@"发送失败");
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"订单获取失败" animated:YES];
    }
     */
    
}
- (void)uploadAlipay:(NSString *)orderString {
    __weak typeof(self) weakSelf = self;
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:AppScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = weakSelf.omid;
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            //成功
            statusVC.type = StatusTypePaySuccess;
        } else {
            //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"付款失败" animated:YES];
            statusVC.type = StatusTypePayFail;
        }
        [weakSelf.navigationController pushViewController:statusVC animated:YES];
    }];
}
 
/**
 付款
 */
- (void)uploadPayOrder:(NSString *)payType price:(NSString *)price {
    NSString *payUrl;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.omid forKey:@"omid"];
    if ([payType isEqualToString:@"0"]) {
        payUrl = URL_Pay_Wechat;
    } else if ([payType isEqualToString:@"1"]) {
        payUrl = URL_Pay_Alipay;
    } else {
        payUrl = URL_Pay_Balance;
        [dic setObject:price forKey:@"price"];
    }
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:payUrl parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([payType isEqualToString:@"2"]) {
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.osid = blockSelf.omid;
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                statusVC.type = StatusTypePaySuccess;
            } else {
                statusVC.type = StatusTypePayFail;
            }
            [blockSelf.navigationController pushViewController:statusVC animated:YES];
        } else if ([responseObject[@"code"] isEqualToString:@"200"]) {
            if ([payType isEqualToString:@"1"]) {
                [blockSelf uploadAlipay:responseObject[@"data"]];
            } else if ([payType isEqualToString:@"0"]) {
                [blockSelf uploadWechatPay:responseObject[@"data"]];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)payAction:(OrderModel *)model {
    NSLog(@"付款 %@",model.omid);
    [self.payView.priceLabel setHidden:NO];
    [self.payView.priceTF setHidden:YES];
    
    [self.payView.priceLabel setText:[NSString stringWithFormat:@"¥%@",model.omprice]];
    
    self.omid = model.omid;
    [self.payView showView];
    
    __block typeof(self) blockSelf = self;
    self.payView.block = ^(NSString *payType, NSString *rechargeStr) {
        [blockSelf uploadPayOrder:payType price:rechargeStr];
    };
}
/**
 取消订单
 */
- (void)cancelAction:(OrderModel *)model {
    __block typeof(self) blockSelf = self;
    [self showAlertWithTitleArray:@[@"取消",@"确认"] title:@"温馨提示" message:@"确认取消此订单？" alertStyle:UIAlertControllerStyleAlert];
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确认"]) {
            NSLog(@"取消订单 %@",model.omid);
            NSString *url = URL_Cancel_Order;
            if (blockSelf.classType == MineOrderClassTypeGroup) {
                url = URL_Cancel_Group_Order;
            }
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [MYAFNetworking POST:url parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"已取消该订单" animated:YES];
                    [blockSelf reloadData];
                } else {
                    [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    };
    
}
/**
 提醒发货
 */
- (void)alertAction:(OrderModel *)model {
    NSLog(@"  %@",model.omid);
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Order_Remind_Shipment parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"已提醒卖家发货，请耐心等待" animated:YES];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
/**
 查看物流
 */
- (void)checkAction:(OrderModel *)model {
    NSLog(@"查看物流 %@",model.omid);
    // 点击“查看物流”按钮时跳转
    LogisticsWebViewController *logisticsVC = [[LogisticsWebViewController alloc] init];
    logisticsVC.com = model.lccode;
    logisticsVC.nu = model.omlogisticsnumber;
//    LogisticsViewController *logisticsVC = [[LogisticsViewController alloc] init];
//    logisticsVC.orderID = model.omid;
    [self.navigationController pushViewController:logisticsVC animated:YES];

}
/**
 确认收货
 */
- (void)sureAction:(OrderModel *)model {
    NSLog(@"确认收货 %@",model.omid);
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Confirm_Receipt parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self reloadData];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
/**
 删除订单
 */
- (void)deleteAction:(OrderModel *)model {
    __block typeof(self) blockSelf = self;
    [self showAlertWithTitleArray:@[@"取消",@"确定"] title:@"温馨提示" message:@"确认删除此订单？" alertStyle:UIAlertControllerStyleAlert];
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确定"]) {
            NSLog(@"删除订单 %@",model.omid);
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [MYAFNetworking POST:URL_Delete_Order parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"已删除该订单" animated:YES];
                    [blockSelf reloadData];
                } else {
                    [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    };
}
/**
 评价
 */
- (void)evaluateAction:(OrderModel *)model {
    NSLog(@"评价 %@",model.omid);
    // 点击“评价”按钮时跳转
    EvaluateViewController *evaluateVC = [[EvaluateViewController alloc] init];
    for (OrdersonModel *temp in model.ordergoods) {
        EvaluateModel *model = [[EvaluateModel alloc] init];
        model.orderson_model = temp;
        model.gid = temp.gid;
        model.ogid = temp.ogid;
        model.escore = @"5";
        model.econtent = @"";
        model.eiimgs = @"";
        model.isanonymous = NO;
        
        [evaluateVC.tableArray addObject:model];
    }
    evaluateVC.block = ^(BOOL isEvaluateOrder) {
        if (isEvaluateOrder) {
            [self reloadData];
        }
    };
    [self.navigationController pushViewController:evaluateVC animated:YES];

}

/**
 查看他人店铺
 */
- (void)clickHeaderCheckStore:(OrderModel *)model {
    NSLog(@"查看他人店铺");
    /*
    ShopModel *shopModel = model.shop;
    if (![shopModel.sid isEqualToString:@"0"]) {
//        OthersStoreViewController *otherStoreVC = [[OthersStoreViewController alloc] init];
//        otherStoreVC.mid = shopModel.mid;
//        [self.navigationController pushViewController:otherStoreVC animated:YES];
    }
     */
}
// 逛一逛 跳转到聊天
- (void)GuangYiGuangGotoChatWithItem:(OrderModel *)item {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:item.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Other_Member_Info parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic  safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *modelDic = [responseDic safeJsonObjectForKey:@"data"];
            OthersMemberInfoModel *model = [OthersMemberInfoModel mj_objectWithKeyValues:modelDic];
            
            /*
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:model.mid name:model.mnickname portrait:model.mimg];
            [[RCIM sharedRCIM]
             refreshUserInfoCache:updatedUserInfo
             withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = model.mid;
            // title
            chatVC.title = model.mnickname;
            //// 传入商品链接
            //charVC.gid = item.gid;
            //charVC.gname = item.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

// 哈哈商城
- (void)getCustomerInfo:(OrderModel *)itemModel {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //    [parameters safeSetObject:itemModel.shop.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Customer parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            /*
            CustomerModel *customerModel = [CustomerModel mj_objectWithKeyValues:data];
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:customerModel.rcid name:customerModel.uname portrait:customerModel.img];
            [[RCIM sharedRCIM]
             refreshUserInfoCache:updatedUserInfo
             withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = updatedUserInfo.userId;
            // title
            chatVC.title = updatedUserInfo.name;
            //// 传入商品链接
            //charVC.gid = itemModel.gid;
            //charVC.gname = itemModel.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

#pragma mark - 网络请求
- (void)getNetData {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:PageSize forKey:@"pageSize"];
    
    NSInteger page = 1;NSString *type;
    // 状态（空字符串是全部，0已提交，1已付款，2已发货，3已签收，4已评价，7退款申请，8已退款
    switch (self.type) {
        case MineOrderTypeAll: // 全部
            page = _pageAll;
            type = @"";
            break;
        case MineOrderTypeObligation: // 待付款 -> 已提交
            page = _pageObligation;
            type = @"0";
            break;
        case MineOrderTypeDelivery: // 待发货 -> 已付款
            page = _pageDelivery;
            type = @"1";
            break;
        case MineOrderTypeReceived: // 待收货 -> 已发货
            page = _pageReceived;
            type = @"2";
            break;
        case MineOrderTypeEvaluation: // 待评价 -> 已签收
            page = _pageEvaluation;
            type = @"3";
            break;
        default:
            break;
    }
    [dic setObject:@(page) forKey:@"pageNumber"];
    [dic setObject:type forKey:@"omstatus"];
    
     NSString *url = URL_Get_Order;
    if (self.soldType == 0) {
        if (self.classType == MineOrderClassTypeGroup) {
            url = URL_Get_Group_Order;
        }
    }else{
        [dic setObject:self.sxid forKey:@"sxid"];
        [dic setObject:self.goodsType forKey:@"sxtype"];
        url = @"api2/getshoporder";
    }
    // 获取订单列表接口
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
            [self getNetSuccess:dics];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"data"] animated:YES];
            [self getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
        [self getNetFailure];
    }];
    
}
- (void)getNetStatusData {
    NSString *url;
    switch (self.classType) {
        case MineOrderClassTypeNormal:
        {
            url = URL_Get_Order_Status;
        } break;
        case MineOrderClassTypeGroup:
        {
            url = URL_Get_Group_Order_Status;
        } break;
        default:
            break;
    }
    if (self.soldType == 1) {
        url = @"api2/getshoporderstatus";
    }
    
    [MYAFNetworking POST:url parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *code = responseObject[@"code"];
        if ([code isEqualToString:@"200"]) {
            [self.headerTitleArray removeAllObjects];
            
            NSArray *arr = responseObject[@"data"];
            NSMutableDictionary *statusDic = [[NSMutableDictionary alloc] init];
            for (NSInteger i = 0; i < arr.count; i++) {
                [statusDic setObject:arr[i] forKey:[NSString stringWithFormat:@"status%ld",i]];
            }
            OrderStatusModel *statusModel = [OrderStatusModel mj_objectWithKeyValues:statusDic];
            
            [self.headerTitleArray addObject:@{@"title":@"全部",@"number":@"0"}];
            [self.headerTitleArray addObject:@{@"title":@"待付款",@"number":statusModel.status0}];
            switch (self.classType) {
                case MineOrderClassTypeNormal:
                {
                    [self.headerTitleArray addObject:@{@"title":@"待发货",@"number":statusModel.status1}];
                    [self.headerTitleArray addObject:@{@"title":@"待收货",@"number":statusModel.status2}];
                    [self.headerTitleArray addObject:@{@"title":@"待评价",@"number":statusModel.status3}];
                } break;
                case MineOrderClassTypeGroup:
                {
                    [self.headerTitleArray addObject:@{@"title":@"拼团中",@"number":statusModel.status2}];
                    [self.headerTitleArray addObject:@{@"title":@"待收货",@"number":statusModel.status3}];
                    [self.headerTitleArray addObject:@{@"title":@"待评价",@"number":statusModel.status5}];
                } break;
                default:
                    break;
            }
            
            [self updateHeaderView];
//            [self.tableView reloadData];
        } else if (![code isEqualToString:@"204"]) {
//            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:code animated:YES];
        } else {
            [[UserInfo shareInstance] logout];
            
            [self.headerTitleArray removeAllObjects];
            [self.headerTitleArray addObject:@{@"title":@"全部",@"number":@"0"}];
            [self.headerTitleArray addObject:@{@"title":@"待付款",@"number":@"0"}];
            switch (self.classType) {
                case MineOrderClassTypeNormal:
                {
                    [self.headerTitleArray addObject:@{@"title":@"待发货",@"number":@"0"}];
                } break;
                case MineOrderClassTypeGroup:
                {
                    [self.headerTitleArray addObject:@{@"title":@"拼团中",@"number":@"0"}];
                } break;
                default:
                    break;
            }
            [self.headerTitleArray addObject:@{@"title":@"待收货",@"number":@"0"}];
            [self.headerTitleArray addObject:@{@"title":@"待评价",@"number":@"0"}];
            [self updateHeaderView];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    switch (self.type) {
        case MineOrderTypeAll:
            return self.tableArrayAll.count;
        case MineOrderTypeObligation:
            return self.tableArrayObligation.count;
        case MineOrderTypeDelivery:
            return self.tableArrayDelivery.count;
        case MineOrderTypeReceived:
            return self.tableArrayReceived.count;
        case MineOrderTypeEvaluation:
            return self.tableArrayEvaluation.count;
        default:
            return 0;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.type) {
        case MineOrderTypeAll:
            return self.tableArrayAll[section].ordergoods.count+3;
        case MineOrderTypeObligation:
            return self.tableArrayObligation[section].ordergoods.count+3;
        case MineOrderTypeDelivery:
            return self.tableArrayDelivery[section].ordergoods.count+3;
        case MineOrderTypeReceived:
            return self.tableArrayReceived[section].ordergoods.count+3;
        case MineOrderTypeEvaluation:
            return self.tableArrayEvaluation[section].ordergoods.count+3;
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderModel *model;
    switch (self.type) {
        case MineOrderTypeAll:
            model = self.tableArrayAll[indexPath.section];
            break;
        case MineOrderTypeObligation:
            model = self.tableArrayObligation[indexPath.section];
            break;
        case MineOrderTypeDelivery:
            model = self.tableArrayDelivery[indexPath.section];
            break;
        case MineOrderTypeReceived:
            model = self.tableArrayReceived[indexPath.section];
            break;
        case MineOrderTypeEvaluation:
            model = self.tableArrayEvaluation[indexPath.section];
            break;
        default:
            break;
    }
    // 按钮点击事件回调
    MineOrderTableViewCell *cell = [MineOrderTableViewCell mineOrderCellWith:tableView indexPath:indexPath count:model.ordergoods.count];
    [cell updateCellWith:model indexPath:indexPath];
    cell.orderBlock = ^(OrderButtonType type, NSInteger tag) {
        if (self.soldType == 1) {
            return;
        }
        switch (type) {
            case OrderButtonTypePay:
            {
                [self payAction:model];
            } break;
            case OrderButtonTypeCancel:
            {
                [self cancelAction:model];
            } break;
            case OrderButtonTypeAlert:
            {
                [self alertAction:model];
            } break;
            case OrderButtonTypeSure:
            {
                [self sureAction:model];
            } break;
            case OrderButtonTypeCheck:
            {
                [self checkAction:model];
            } break;
            case OrderButtonTypeDelete:
            {
                [self deleteAction:model];
            } break;
            case OrderButtonTypeEvaluate:
            {
                [self evaluateAction:model];
            } break;
            case OrderButtonTypeRefundDetail:
            {
                RefundDetailViewController *refundDetailVC = [[RefundDetailViewController alloc] init];
                refundDetailVC.detailModel = model;
                refundDetailVC.type = RefundFromTypeSelfOrder;
                [self.navigationController pushViewController:refundDetailVC animated:YES];
            } break;
            case OrderButtonTypeService:
            {
                NSLog(@"联系客服");
                [self goToServiceChat];
                /*
                if ([model.shop.sid isEqualToString:@"0"]) {
                    // 自营
                    [self getCustomerInfo:model];
                } else {
                    // 个人、企业
                    [self GuangYiGuangGotoChatWithItem:model];
                }
                 */
            } break;
            default:
                break;
        }
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderModel *model;
    switch (self.type) {
        case MineOrderTypeAll:
            model = self.tableArrayAll[indexPath.section];
            break;
        case MineOrderTypeObligation:
            model = self.tableArrayObligation[indexPath.section];
            break;
        case MineOrderTypeDelivery:
            model = self.tableArrayDelivery[indexPath.section];
            break;
        case MineOrderTypeReceived:
            model = self.tableArrayReceived[indexPath.section];
            break;
        case MineOrderTypeEvaluation:
            model = self.tableArrayEvaluation[indexPath.section];
            break;
        default:
            break;
    }
    if (indexPath.row == 0) {
        return 44.0;
    } else if (indexPath.row == model.ordergoods.count+1) {
        return 44.0;
    } else if (indexPath.row == model.ordergoods.count+2) {
        if (self.soldType == 1) {
            return 0;
        }
        return 47.0;
    } else {
        return 112;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    switch (self.type) {
        case MineOrderTypeAll:
        {
            if (section < self.tableArrayAll.count-1) {
                return 10;
            }
            return 0;
        }
        case MineOrderTypeObligation:
        {
            if (section < self.tableArrayObligation.count-1) {
                return 10;
            }
            return 0;
        }
        case MineOrderTypeDelivery:
        {
            if (section < self.tableArrayDelivery.count-1) {
                return 10;
            }
            return 0;
        }
        case MineOrderTypeReceived:
        {
            if (section < self.tableArrayReceived.count-1) {
                return 10;
            }
            return 0;
        }
        case MineOrderTypeEvaluation:
        {
            if (section < self.tableArrayEvaluation.count-1) {
                return 10;
            }
            return 0;
        }
        default:
            return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 10)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.soldType == 1) {
        return;
    }
    OrderModel *model;
    switch (self.type) {
        case MineOrderTypeAll:
            model = self.tableArrayAll[indexPath.section];
            break;
        case MineOrderTypeObligation:
            model = self.tableArrayObligation[indexPath.section];
            break;
        case MineOrderTypeDelivery:
            model = self.tableArrayDelivery[indexPath.section];
            break;
        case MineOrderTypeReceived:
            model = self.tableArrayReceived[indexPath.section];
            break;
        case MineOrderTypeEvaluation:
            model = self.tableArrayEvaluation[indexPath.section];
            break;
        default:
            break;
    }
    
//    if (indexPath.row == 0) {
//        [self clickHeaderCheckStore:model];
//        return;
//    }
    if (!model.isrefund) {
        OrderDetailViewController *detailVC = [[OrderDetailViewController alloc] init];
        detailVC.detailModel = model;
        detailVC.fromType = FromTypeSelfOrder;
        detailVC.block = ^(BOOL cancelOrder) {
            if (cancelOrder) {
                [MBProgressHUD showHUDProgress:self.view animated:YES];
                [self reloadData];
            }
        };
        [self.navigationController pushViewController:detailVC animated:YES];
    } else {
        RefundDetailViewController *refundDetailVC = [[RefundDetailViewController alloc] init];
        refundDetailVC.detailModel = model;
        refundDetailVC.type = RefundFromTypeSelfOrder;
        [self.navigationController pushViewController:refundDetailVC animated:YES];
    }
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无订单"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    //    [self startLoadingGifView];
    [self reloadData];
}

- (DYShopOrderFooterView *)footerView{
    if (!_footerView) {
        _footerView = [[DYShopOrderFooterView alloc] init];
        __weak typeof(self)weakSelf = self;
        self.goodsType = @"1";
        _footerView.didSelectedFooterBlock = ^(NSInteger tag) {
            NSInteger value = tag;
            if (tag == 0) {
                value = 1;
            }else{
                value = 2;
            }
            weakSelf.goodsType = [NSString stringWithFormat:@"%ld",tag];
            [weakSelf getNetData];
            [weakSelf getNetStatusData];
        };
    }
    return _footerView;
}

@end
